package com.wayne.config;

import com.wayne.pojo.Configuration;
import com.wayne.pojo.MappedStatement;
import com.wayne.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class XMLMapperBuilder {
  private Configuration configuration;

  public XMLMapperBuilder(Configuration configuration) {
    this.configuration = configuration;
  }

  public void parse(InputStream inputStream) {
    Document document = null;
    try {
      document = new SAXReader().read(inputStream);
    } catch (DocumentException e) {
      e.printStackTrace();
    }
    if (document == null) {
      return;
    }
    Element rootElement = document.getRootElement();
    String namespace = rootElement.attributeValue("namespace");
    List<Element> selectList = rootElement.selectNodes("//select");
    List<Element> insertList = rootElement.selectNodes("//insert");
    List<Element> updateList = rootElement.selectNodes("//update");
    List<Element> deleteList = rootElement.selectNodes("// delete");
    List<Element> curdList = new ArrayList<>();
    curdList.addAll(selectList);
    curdList.addAll(insertList);
    curdList.addAll(updateList);
    curdList.addAll(deleteList);
    curdList.stream().forEach(element -> addMappedStatement(namespace, element));
  }

  private void addMappedStatement(String namespace, Element element) {
    MappedStatement mappedStatement = new MappedStatement();
    mappedStatement.setId(element.attributeValue("id"));
    mappedStatement.setParameterType(element.attributeValue("parameterType"));
    mappedStatement.setResultType(element.attributeValue("resultType"));
    mappedStatement.setSql(element.getTextTrim());
    SqlCommandType sqlCommandType = SqlCommandType.valueOf(element.getName().toUpperCase(Locale.ENGLISH));
    mappedStatement.setSqlCommandType(sqlCommandType);
    String key = String.format("%s.%s", namespace, mappedStatement.getId());
    configuration.getMappedStatementMap().put(key, mappedStatement);
  }
}
